# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: twl
@date: 2020/4/14 18:18
@description:
"""

from flask import jsonify

from base.entity.base_entity import BaseEntity
from base.model.base_model import BaseModel
import ujson

class JsonUtil(object):
	
	@staticmethod
	def loads(data):
		return ujson.loads(data)
	
	@staticmethod
	def loads(data):
		return ujson.loads(data)
	
	@staticmethod
	def dumps(data):
		data = data.__dict__ if isinstance(data, BaseEntity) or isinstance(data, BaseModel) else data
		return ujson.dumps(data, ensure_ascii=False)
	
	@staticmethod
	def obj2json(data):
		if isinstance(
			data,
			list) and len(data) > 0 and isinstance(
			data[0],
			BaseEntity):
			data_output = []
			for obj_data in data:
				obj_json = obj_data.to_json()
				data_output.append(obj_json)
			return jsonify(data_output)
		if isinstance(data, object) and isinstance(data, BaseEntity):
			obj_json = data.to_json()
			return jsonify(obj_json)
		return jsonify(data)
	
	@staticmethod
	def response_success(data):
		if isinstance(
			data,
			list) and len(data) > 0 and (
			isinstance(
				data[0],
				BaseEntity) or isinstance(
			data[0],
			BaseModel)):
			data_output = []
			for obj_data in data:
				obj_json = obj_data.to_json()
				data_output.append(obj_json)
			return jsonify(code='0', data=data_output, msg='success')
		if isinstance(
			data,
			object) and (
			isinstance(
				data,
				BaseEntity) or isinstance(
			data,
			BaseModel)):
			obj_json = data.to_json()
			return jsonify(code='0', data=obj_json, msg='success')
		return jsonify(code='0', data=data, msg='success')
	
	@staticmethod
	def response_success_page(rows, total=None):
		result = dict()
		if isinstance(
			rows,
			list) and len(rows) > 0 and (
			isinstance(
				rows[0],
				BaseEntity) or isinstance(
			rows[0],
			BaseModel)):
			data_output = []
			for obj_data in rows:
				obj_json = obj_data.to_json()
				data_output.append(obj_json)
			result['rows'] = data_output
			if total is None:
				total = len(rows)
			result['total'] = total
			return jsonify(code='0', data=result, msg='success')
		result['rows'] = rows
		result['total'] = total
		return jsonify(code='0', data=result, msg='success')
	
	@staticmethod
	def response_fail(msg='system exec error'):
		return jsonify(code='1001', data=None, msg=msg)
